package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

/**
 * @Author ZhangGJ
 * @Date 2022/02/22 14:18
 */
public class NIOServer {

	public static void main(String[] args) throws IOException, InterruptedException {
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		serverSocketChannel.bind(new InetSocketAddress(9999));
		serverSocketChannel.configureBlocking(false);
		System.out.println("=============服务端启动成功");
		while (true) {
			SocketChannel socketChannel = serverSocketChannel.accept();
			if (socketChannel == null) {
				System.out.println("==============没有客户端连接");
				Thread.sleep(2000);
				continue;
			}
			ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
			int read = socketChannel.read(byteBuffer);
			System.out.println(
					"客户端消息: " + new String(byteBuffer.array(), 0, read, StandardCharsets.UTF_8));
			socketChannel.write(ByteBuffer.wrap("OK".getBytes(StandardCharsets.UTF_8)));
			socketChannel.close();
		}
	}
}
